package com.simple.portal.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.simple.portal.bo.IGroupInfoBO;
import com.simple.portal.bo.IOrganizationBO;
import com.simple.portal.bo.ISendMailBO;
import com.simple.portal.bo.IUserGroupRelBO;
import com.simple.portal.bo.IUserInfoBO;
import com.simple.portal.vo.GroupInfoVO;
import com.simple.portal.vo.OrganizationVO;
import com.simple.portal.vo.UserGroupRelVO;
import com.simple.portal.vo.UserInfoVO;
import com.simple.util.TbResourceLoad;
import com.simple.util.common.Constants;
import com.simple.util.common.EncryptUtil;
import com.simple.util.common.ErrorUtil;
import com.simple.util.common.RightsConstants;
import com.simple.util.exception.SimpleApplicationException;
import com.simple.util.object.JFValidationBean;
import com.simple.util.object.PageInfoBean;
import com.simple.util.object.portal.SessionUserBean;

import freemarker.template.TemplateException;

@Controller
@RequestMapping("/user")
public class UserController extends AbstractPortalBaseController{
	private final static String JSP_PATH = "_User";
	
	@Autowired
	private IUserInfoBO  userInfoBO;
	@Autowired
	private IUserGroupRelBO  userGroupRelBO;
	@Autowired
	private IOrganizationBO organizationBO;
	@Autowired
	private IGroupInfoBO groupInfoBO;
	@Autowired
	private ISendMailBO sendMailBO;

	@RequestMapping("/system/list")  
    public String systemList(
    		@RequestParam(value="pageNo",required=false,defaultValue="1") Integer pageNo,
    		@RequestParam(value="userIdSearch",required=false) String userIdSearch,
			@RequestParam(value="userNameSearch",required=false) String userNameSearch,
			@RequestParam(value="mobilePhoneSearch",required=false) String mobilePhoneSearch,
			@RequestParam(value="statusSearch",required=false) String statusSearch,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_LIST);
		if(flag){
		        final PageInfoBean pageInfoBean = new PageInfoBean(pageNo);
		        SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
		        List<UserInfoVO> UserInfoVoList = userInfoBO.findUserInfoByPage(sessionUserBean.getUserInfoVO().getUserId(), userIdSearch, userNameSearch, mobilePhoneSearch, statusSearch, pageInfoBean);
				Map<String, String> statusMap= TbResourceLoad.getInstance().getMap(Constants.TBRESOURCES_PACKAGE_MAP_STATUS, getSiteLanguage(request));
		        request.setAttribute("UserInfoVoList", UserInfoVoList);
		        request.setAttribute("statusMap", statusMap);
				 
				final String pageInfo = super.generatePageInfo(request,response,pageInfoBean, "goPage");
			    request.setAttribute("pageInfo", pageInfo);  
			    
			    request.setAttribute("pageNo", pageNo); 
			    request.setAttribute("userIdSearch", userIdSearch);  
			    request.setAttribute("userNameSearch", userNameSearch);  
			    request.setAttribute("mobilePhoneSearch", mobilePhoneSearch);  
			    request.setAttribute("statusSearch", statusSearch); 
			    request.setAttribute("type", "system"); 
			    request.setAttribute("statusOne", Constants.STATE_NORMAL);
			    request.setAttribute("statusZero", Constants.STATE_STOP);
			    request.setAttribute("recordCountInOnePage", PageInfoBean.COMMON_RECORD_COUNT_IN_ONE_PAGE);
		}
			    
        return getJspPath("user_info_list");
    }
	
	@RequestMapping("/system/view")  
    public String systemInfo(
    		@RequestParam(value="userIdH",required=false) String userId,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_LIST);
		if(flag){
			UserInfoVO userInfoVO = userInfoBO.findById(userId);
			
			Map<String, String> statusMap= TbResourceLoad.getInstance().getMap(Constants.TBRESOURCES_PACKAGE_MAP_STATUS, getSiteLanguage(request));
			request.setAttribute("statusMap", statusMap);
			Map<String, String> typeMap= TbResourceLoad.getInstance().getMap(Constants.TBRESOURCES_PACKAGE_MAP_USER_TYPE, getSiteLanguage(request));
			request.setAttribute("typeMap", typeMap);
			
			List<UserGroupRelVO> userGroupRelVOList = userGroupRelBO.findByUserId(userId);
			OrganizationVO organizationVO = organizationBO.findById(userInfoVO.getOrganizationId());
			String loginId = EncryptUtil.decrypt(userInfoVO.getLoginId());
			
			request.setAttribute("organizationVO", organizationVO);
			request.setAttribute("userGroupRelVOList", userGroupRelVOList);
			request.setAttribute("userInfoVO", userInfoVO);
			request.setAttribute("loginId", loginId);
			request.setAttribute("type", "system"); 
		}
        return getJspPath("user_info_view");
    }
	
	@RequestMapping("/system/add")  
    public String systemAdd(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_ADD);
		if(flag){
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			List<GroupInfoVO> groupInfoVOList = groupInfoBO.findByCreator(sessionUserBean.getUserInfoVO().getUserId());
			request.setAttribute("groupInfoVOList", groupInfoVOList);
			request.setAttribute("type", "system");
			return getJspPath("user_info_add");
		}
		return "forward:/user/system/list";
    }
	
	@RequestMapping("/system/addSubmit")
    public String systemAddSubmit(
    		@ModelAttribute("userInfoVO") UserInfoVO userInfoVO,
    		@RequestParam(value="groupId",required=false) String groupId,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_ADD);
		if(flag){
			final List<JFValidationBean> errorList = getErrorList();
			String siteLanguage = getSiteLanguage(request);
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			String loginId = userInfoBO.addUserInfo(sessionUserBean, userInfoVO, groupId, siteLanguage);
			//q1
			try {
				//confirm the "add" operation succeeded
				userInfoVO = userInfoBO.findByLoginId(loginId);
				if(userInfoVO != null){
					//get userId via loginId
					sendMailBO.sendRegisterAckMail(siteLanguage, userInfoVO.getUserId(), sessionUserBean.getUserInfoVO().getUserId());
				}else{
					errorList.add(new JFValidationBean(""));
				}
			} catch (SimpleApplicationException e) {
				errorList.add(ErrorUtil.generateJFValidationFromAppException(e));
			}
		}
        return "forward:/user/system/list";
    }
	
	@RequestMapping("/system/edit")  
    public String systemEdit(
    		@RequestParam(value="userIdH",required=false) String userId,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {

		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_EDIT);
		if(flag){
			UserInfoVO userInfoVO = userInfoBO.findById(userId);
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			Map<String, String> statusMap= TbResourceLoad.getInstance().getMap(Constants.TBRESOURCES_PACKAGE_MAP_STATUS, getSiteLanguage(request));
			request.setAttribute("statusMap", statusMap);
			Map<String, String> typeMap= TbResourceLoad.getInstance().getMap(Constants.TBRESOURCES_PACKAGE_MAP_USER_TYPE, getSiteLanguage(request));
			request.setAttribute("typeMap", typeMap);
			List<GroupInfoVO> groupInfoVOList = groupInfoBO.findByCreator(sessionUserBean.getUserInfoVO().getUserId());
			
//			List<UserGroupRelVO> userGroupRelVOList = userGroupRelBO.findByUserId(userId);
//			OrganizationVO organizationVO = organizationBO.findById(userInfoVO.getOrganizationId());
			//q2
			String groupId = userGroupRelBO.findByUserId(userId).get(0).getGroupId();
			String loginId = EncryptUtil.decrypt(userInfoVO.getLoginId());
			request.setAttribute("loginId", loginId);
			request.setAttribute("groupInfoVOList", groupInfoVOList);
//			request.setAttribute("organizationVO", organizationVO);
//			request.setAttribute("userGroupRelVOList", userGroupRelVOList);
			request.setAttribute("userInfoVO", userInfoVO);
			request.setAttribute("groupId", groupId);
			request.setAttribute("type", "system"); 
		}
        return getJspPath("user_info_edit");
    }
	
	@RequestMapping("/system/editSubmit")  
    public String systemEditSubmit(
    		@ModelAttribute("userInfoVO") UserInfoVO userInfoVO,
    		@RequestParam(value="groupId",required=false) String groupId,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_EDIT);
		if(flag){
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			userInfoBO.update(sessionUserBean, userInfoVO, groupId);
		}
		
		return "forward:/user/system/list";
	}
	@RequestMapping("/system/control")  
    public String systemControl(
    		@RequestParam(value="userIdH",required=false) String userId,
    		@RequestParam(value="statusH",required=false) String status,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {

		boolean flag= checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_CONTROL);
		if(flag){
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			userInfoBO.controlUserInfo(sessionUserBean, userId, status);
		}
		return "forward:/user/system/list";
    }
	
	@RequestMapping("/system/reset")  
    public String systemReset(
    		@RequestParam(value="userIdH",required=false) String userId,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		
		boolean flag= checkRights( request,response,RightsConstants.FUNC_USER_STSTEM_CONTROL);
		if(flag){
			final List<JFValidationBean> errorList = getErrorList();
			SessionUserBean sessionUserBean = getCurrentSessionUserBean(request);
			try {
				sendMailBO.sendPasswordResetMail(getSiteLanguage(request), userId, sessionUserBean.getUserInfoVO().getUserId());
			} catch (SimpleApplicationException e) {
				errorList.add(ErrorUtil.generateJFValidationFromAppException(e));
			}
		}
        return "forward:/user/system/list";
    }
	
	
	@RequestMapping("/enterprise/list")  
    public String enterpriseList(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {

        
        return getJspPath("enterprise_list");
    }
	
	@RequestMapping("/enterprise/add")  
    public String enterpriseAdd(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("enterprise_add");
    }
	
	@RequestMapping("/enterprise/edit")  
    public String enterpriseEdit(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("enterprise_edit");
    }
	
	@RequestMapping("/enterprise/control")  
    public void enterpriseControl(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
       
    }
	
	@RequestMapping("/enterprise/reset")  
    public String enterpriseReset(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("enterprise_reset");
    }
	
	@RequestMapping("/partner/list")  
    public String partnerList(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("partner_list");
    }
	
	@RequestMapping("/partner/add")  
    public String partnerAdd(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("partner_add");
    }
	
	@RequestMapping("/partner/edit")  
    public String partnerEdit(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("partner_edit");
    }
	
	@RequestMapping("/partner/control")  
    public void partnerControl(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
       
    }
	
	@RequestMapping("/partner/reset")  
    public String partnerReset(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("partner_reset");
    }
	
	@RequestMapping("/self/edit")  
    public String selfedit(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
        
        return getJspPath("self_edit");
    }
	
	@RequestMapping("/self/editpassword")  
    public String selfEditPassword(@RequestParam(value="password",required=false) String password,
    		@RequestParam(value="passwordNew",required=false) String passwordNew,
    		@RequestParam(value="passwordConfirm",required=false) String passwordConfirm,
    		@RequestParam(value="editSuccess",required=false) String editSuccess,
    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException  {
		boolean flag = checkRights( request,response,RightsConstants.FUNC_USER_SELF_EDIT_PASSWORD);
		if(flag){
		 request.setAttribute("password", password);
		 request.setAttribute("passwordNew", passwordNew);
		 request.setAttribute("passwordConfirm", passwordConfirm);
		 request.setAttribute("editSuccess", editSuccess);
		}
        return getJspPath("self_editpassword");
    }
	
	@RequestMapping(value="/self/editPasswordSubmit")  
    public String editPasswordSubmit(@RequestParam(value="password",required=false) String password,
    		@RequestParam(value="passwordNew",required=false) String passwordNew,
    		@RequestParam(value="passwordConfirm",required=false) String passwordConfirm,
			    		final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException ,SimpleApplicationException {
		final List<JFValidationBean> errorList = getErrorList();
		final UserInfoVO userInfoVO = super.getCurrentSessionUserBean(request).getUserInfoVO();
		String editSuccess = Constants.STATE_NO;
		try {
			userInfoBO.editPassword(userInfoVO, password, passwordNew, passwordConfirm);
			editSuccess = Constants.STATE_YES;
		} catch (SimpleApplicationException e) {
			errorList.add(ErrorUtil.generateJFValidationFromAppException(e));
		}
		
        return selfEditPassword(password, passwordNew, passwordConfirm,editSuccess, request, response);
    }
	
	@RequestMapping(value="/self/editPasswordSuccessSubmit")  
    public String editPasswordSuccessSubmit(final HttpServletRequest request, final HttpServletResponse response){
		 return "forward:/logout";
	}
	
	@RequestMapping(value="/self/cancelEditPasswordSubmit")  
    public String cancelEditPasswordSubmit(final HttpServletRequest request, final HttpServletResponse response) throws IOException, TemplateException{
		return "forward:/index/init";
	}
	
	@Override
    protected String getBaseJspPath() {
        return JSP_PATH;
    }
	
}

